<template>
  <div class="extra-service">
    <el-card>
      <el-tabs v-model="activeTab">
        <!-- 手续费设置 -->
        <el-tab-pane label="手续费设置" name="service-fee">
          <div class="section">
            <!-- 站点选择器 -->
            <div class="site-selector">
              <el-select v-model="selectedSite" placeholder="选择站点" style="width: 200px; margin-bottom: 20px;" @change="onSiteChange">
                <el-option label="全部站点" value="all" />
                <el-option v-for="site in siteOptions" :key="site.value" :label="site.label" :value="site.value" />
              </el-select>
            </div>

            <!-- 按站点分组显示手续费设置 -->
            <div v-if="selectedSite === 'all'" class="site-groups">
              <!-- B端客户手续费 - 按站点分组 -->
              <div class="site-group">
                <h3 class="site-group-title">
                  <el-icon><User /></el-icon>
                  B端客户手续费
                </h3>
                <div v-for="site in getUniqueSites('B')" :key="site" class="site-section">
                  <div class="site-header">
                    <h4 class="site-name">
                      <el-icon><Platform /></el-icon>
                      {{ site }}
                    </h4>
                    <el-button type="primary" size="small" @click="openServiceFeeDialog('add', 'B', undefined, undefined, site)">
                      <el-icon><Plus /></el-icon>
                      新增
                    </el-button>
                  </div>
                  <el-table 
                    :data="getServiceFeesBySite('B', site)" 
                    style="width: 100%; margin-bottom: 20px;" 
                    :border="false"
                    :stripe="true"
                    class="custom-table"
                  >
                    <el-table-column prop="minAmount" label="区间下限（日元）" width="140" align="center">
                      <template #default="scope">
                        <span class="amount-text">{{ scope.row.minAmount.toLocaleString() }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column prop="maxAmount" label="区间上限（日元）" width="140" align="center">
                      <template #default="scope">
                        <span v-if="scope.row.maxAmount !== null" class="amount-text">{{ scope.row.maxAmount.toLocaleString() }}</span>
                        <span v-else class="no-limit">无上限</span>
                      </template>
                    </el-table-column>
                    <el-table-column prop="fee" label="手续费（日元）" width="140" align="center">
                      <template #default="scope">
                        <span class="fee-text">{{ scope.row.fee.toLocaleString() }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column label="操作" width="160" align="center">
                      <template #default="scope">
                        <div class="action-buttons">
                          <el-button size="small" type="primary" @click="openServiceFeeDialog('edit', 'B', scope.row, scope.$index, site)">
                            <el-icon><Edit /></el-icon>
                            编辑
                          </el-button>
                          <el-button size="small" type="danger" @click="deleteServiceFee(scope.row, scope.$index)">
                            <el-icon><Delete /></el-icon>
                            删除
                          </el-button>
                        </div>
                      </template>
                    </el-table-column>
                  </el-table>
                  
                  <!-- 空状态提示 -->
                  <div v-if="getServiceFeesBySite('B', site).length === 0" class="empty-state">
                    <el-empty description="暂无B端手续费设置" :image-size="80">
                      <el-button type="primary" size="small" @click="openServiceFeeDialog('add', 'B', undefined, undefined, site)">
                        <el-icon><Plus /></el-icon>
                        立即添加
                      </el-button>
                    </el-empty>
                  </div>
                </div>
              </div>

              <!-- C端客户手续费 - 按站点分组 -->
              <div class="site-group">
                <h3 class="site-group-title">
                  <el-icon><UserFilled /></el-icon>
                  C端客户手续费
                </h3>
                <div v-for="site in getUniqueSites('C')" :key="site" class="site-section">
                  <div class="site-header">
                    <h4 class="site-name">
                      <el-icon><Platform /></el-icon>
                      {{ site }}
                    </h4>
                    <el-button type="primary" size="small" @click="openServiceFeeDialog('add', 'C', undefined, undefined, site)">
                      <el-icon><Plus /></el-icon>
                      新增
                    </el-button>
                  </div>
                  <el-table 
                    :data="getServiceFeesBySite('C', site)" 
                    style="width: 100%; margin-bottom: 20px;" 
                    :border="false"
                    :stripe="true"
                    class="custom-table"
                  >
                    <el-table-column prop="minAmount" label="区间下限（日元）" width="140" align="center">
                      <template #default="scope">
                        <span class="amount-text">{{ scope.row.minAmount.toLocaleString() }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column prop="maxAmount" label="区间上限（日元）" width="140" align="center">
                      <template #default="scope">
                        <span v-if="scope.row.maxAmount !== null" class="amount-text">{{ scope.row.maxAmount.toLocaleString() }}</span>
                        <span v-else class="no-limit">无上限</span>
                      </template>
                    </el-table-column>
                    <el-table-column prop="fee" label="手续费（日元）" width="140" align="center">
                      <template #default="scope">
                        <span class="fee-text">{{ scope.row.fee.toLocaleString() }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column label="操作" width="160" align="center">
                      <template #default="scope">
                        <div class="action-buttons">
                          <el-button size="small" type="primary" @click="openServiceFeeDialog('edit', 'C', scope.row, scope.$index, site)">
                            <el-icon><Edit /></el-icon>
                            编辑
                          </el-button>
                          <el-button size="small" type="danger" @click="deleteServiceFee(scope.row, scope.$index)">
                            <el-icon><Delete /></el-icon>
                            删除
                          </el-button>
                        </div>
                      </template>
                    </el-table-column>
                  </el-table>
                  
                  <!-- 空状态提示 -->
                  <div v-if="getServiceFeesBySite('C', site).length === 0" class="empty-state">
                    <el-empty description="暂无C端手续费设置" :image-size="80">
                      <el-button type="primary" size="small" @click="openServiceFeeDialog('add', 'C', undefined, undefined, site)">
                        <el-icon><Plus /></el-icon>
                        立即添加
                      </el-button>
                    </el-empty>
                  </div>
                </div>
              </div>
            </div>

            <!-- 单个站点显示 -->
            <div v-else class="single-site">
              <div class="site-header">
                <h3>
                  <el-icon><Platform /></el-icon>
                  {{ getSiteLabel(selectedSite) }} - 手续费设置
                </h3>
                <div class="header-actions">
                  <el-button type="primary" @click="openServiceFeeDialog('add', 'B', undefined, undefined, selectedSite)">
                    <el-icon><Plus /></el-icon>
                    新增B端设置
                  </el-button>
                  <el-button type="primary" @click="openServiceFeeDialog('add', 'C', undefined, undefined, selectedSite)" style="margin-left: 10px;">
                    <el-icon><Plus /></el-icon>
                    新增C端设置
                  </el-button>
                </div>
              </div>

              <!-- B端客户手续费 -->
              <div class="subsection">
                <h4 class="subsection-title">
                  <el-icon><User /></el-icon>
                  B端客户手续费
                </h4>
                <el-table 
                  :data="getServiceFeesBySite('B', selectedSite)" 
                  style="width: 100%" 
                  :border="false"
                  :stripe="true"
                  class="custom-table"
                >
                  <el-table-column prop="minAmount" label="区间下限（日元）" align="center">
                    <template #default="scope">
                      <span class="amount-text">{{ scope.row.minAmount.toLocaleString() }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="maxAmount" label="区间上限（日元）" align="center">
                    <template #default="scope">
                      <span v-if="scope.row.maxAmount !== null" class="amount-text">{{ scope.row.maxAmount.toLocaleString() }}</span>
                      <span v-else class="no-limit">无上限</span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="fee" label="手续费（日元）" align="center">
                    <template #default="scope">
                      <span class="fee-text">{{ scope.row.fee.toLocaleString() }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="160" align="center">
                    <template #default="scope">
                      <div class="action-buttons">
                        <el-button size="small" type="primary" @click="openServiceFeeDialog('edit', 'B', scope.row, scope.$index, selectedSite)">
                          <el-icon><Edit /></el-icon>
                          编辑
                        </el-button>
                        <el-button size="small" type="danger" @click="deleteServiceFee(scope.row, scope.$index)">
                          <el-icon><Delete /></el-icon>
                          删除
                        </el-button>
                      </div>
                    </template>
                  </el-table-column>
                </el-table>
              </div>

              <!-- C端客户手续费 -->
              <div class="subsection">
                <h4 class="subsection-title">
                  <el-icon><UserFilled /></el-icon>
                  C端客户手续费
                </h4>
                <el-table 
                  :data="getServiceFeesBySite('C', selectedSite)" 
                  style="width: 100%" 
                  :border="false"
                  :stripe="true"
                  class="custom-table"
                >
                  <el-table-column prop="minAmount" label="区间下限（日元）" align="center">
                    <template #default="scope">
                      <span class="amount-text">{{ scope.row.minAmount.toLocaleString() }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="maxAmount" label="区间上限（日元）" align="center">
                    <template #default="scope">
                      <span v-if="scope.row.maxAmount !== null" class="amount-text">{{ scope.row.maxAmount.toLocaleString() }}</span>
                      <span v-else class="no-limit">无上限</span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="fee" label="手续费（日元）" align="center">
                    <template #default="scope">
                      <span class="fee-text">{{ scope.row.fee.toLocaleString() }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="160" align="center">
                    <template #default="scope">
                      <div class="action-buttons">
                        <el-button size="small" type="primary" @click="openServiceFeeDialog('edit', 'C', scope.row, scope.$index, selectedSite)">
                          <el-icon><Edit /></el-icon>
                          编辑
                        </el-button>
                        <el-button size="small" type="danger" @click="deleteServiceFee(scope.row, scope.$index)">
                          <el-icon><Delete /></el-icon>
                          删除
                        </el-button>
                      </div>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </div>
        </el-tab-pane>

        <!-- 服务费率设置 -->
        <el-tab-pane label="服务费率设置" name="service-rate">
          <div class="section">
            <div class="table-actions">
              <el-button type="primary" @click="openServiceRateDialog('add')">新增</el-button>
            </div>
            <el-table :data="serviceRateList" style="width: 100%">
              <el-table-column prop="site" label="站点" />
              <el-table-column prop="rate" label="费率（%）" />
              <el-table-column prop="remark" label="备注" />
              <el-table-column label="操作" width="160">
                <template #default="scope">
                  <div class="action-buttons">
                    <el-button size="small" @click="openServiceRateDialog('edit', scope.row, scope.$index)">编辑</el-button>
                    <el-button size="small" type="danger" @click="deleteServiceRate(scope.row, scope.$index)">删除</el-button>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>

        <!-- 保证金比例设置 -->
        <el-tab-pane label="保证金比例设置" name="deposit-rate">
          <div class="section">
            <div class="table-actions">
              <el-button type="primary" @click="openDepositRateDialog('add')">新增</el-button>
            </div>
            <el-table :data="depositRateList" style="width: 100%">
              <el-table-column prop="site" label="站点" />
              <el-table-column prop="rate" label="保证金比例（%）" />
              <el-table-column prop="remark" label="备注" />
              <el-table-column label="操作" width="160">
                <template #default="scope">
                  <div class="action-buttons">
                    <el-button size="small" @click="openDepositRateDialog('edit', scope.row, scope.$index)">编辑</el-button>
                    <el-button size="small" type="danger" @click="deleteDepositRate(scope.row, scope.$index)">删除</el-button>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
      </el-tabs>

      <!-- 手续费设置弹窗 -->
      <el-dialog v-model="serviceFeeDialog.visible" :title="serviceFeeDialog.mode === 'add' ? '新增手续费' : '编辑手续费'" width="600px" :close-on-click-modal="false">
        <el-form :model="serviceFeeDialog.form" :rules="serviceFeeRules" ref="serviceFeeFormRef" label-width="120px">
          <el-form-item label="客户类型">
            <el-select v-model="serviceFeeDialog.form.type" style="width: 100%">
              <el-option label="B端客户" value="B" />
              <el-option label="C端客户" value="C" />
            </el-select>
          </el-form-item>
          <el-form-item label="站点">
            <el-select v-model="serviceFeeDialog.form.site" style="width: 100%">
              <el-option v-for="site in siteOptions" :key="site.value" :label="site.label" :value="site.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="区间下限" prop="minAmount">
            <el-input-number v-model="serviceFeeDialog.form.minAmount" :min="0" style="width: 100%" />
          </el-form-item>
          <el-form-item label="区间上限" prop="maxAmount">
            <el-input-number v-model="serviceFeeDialog.form.maxAmount" :min="0" style="width: 100%" />
            <span style="color:#888;font-size:12px;">留空或0表示无上限</span>
          </el-form-item>
          <el-form-item label="手续费" prop="fee">
            <el-input-number v-model="serviceFeeDialog.form.fee" :min="0" style="width: 100%" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="serviceFeeDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="saveServiceFee">保存</el-button>
        </template>
      </el-dialog>

      <!-- 服务费率设置弹窗 -->
      <el-dialog v-model="serviceRateDialog.visible" :title="serviceRateDialog.mode === 'add' ? '新增服务费率' : '编辑服务费率'" width="500px" :close-on-click-modal="false">
        <el-form :model="serviceRateDialog.form" :rules="serviceRateRules" ref="serviceRateFormRef" label-width="120px">
          <el-form-item label="站点" prop="site">
            <el-select v-model="serviceRateDialog.form.site" style="width: 100%">
              <el-option label="煤炉" value="煤炉" />
              <el-option label="雅虎日拍" value="雅虎日拍" />
              <el-option label="雅虎闲置" value="雅虎闲置" />
              <el-option label="乐天闲置" value="乐天闲置" />
            </el-select>
          </el-form-item>
          <el-form-item label="费率" prop="rate">
            <el-input-number v-model="serviceRateDialog.form.rate" :min="0" :max="100" :precision="2" style="width: 100%" />
            <span style="color:#888;font-size:12px;">百分比形式，如5.5表示5.5%</span>
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="serviceRateDialog.form.remark" type="textarea" :rows="2" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="serviceRateDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="saveServiceRate">保存</el-button>
        </template>
      </el-dialog>

      <!-- 保证金比例设置弹窗 -->
      <el-dialog v-model="depositRateDialog.visible" :title="depositRateDialog.mode === 'add' ? '新增保证金比例' : '编辑保证金比例'" width="500px" :close-on-click-modal="false">
        <el-form :model="depositRateDialog.form" :rules="depositRateRules" ref="depositRateFormRef" label-width="120px">
          <el-form-item label="站点" prop="site">
            <el-select v-model="depositRateDialog.form.site" style="width: 100%">
              <el-option label="煤炉" value="煤炉" />
              <el-option label="雅虎日拍" value="雅虎日拍" />
              <el-option label="雅虎闲置" value="雅虎闲置" />
              <el-option label="乐天闲置" value="乐天闲置" />
            </el-select>
          </el-form-item>
          <el-form-item label="保证金比例" prop="rate">
            <el-input-number v-model="depositRateDialog.form.rate" :min="0" :max="100" :precision="2" style="width: 100%" />
            <span style="color:#888;font-size:12px;">百分比形式，如10.5表示10.5%</span>
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="depositRateDialog.form.remark" type="textarea" :rows="2" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="depositRateDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="saveDepositRate">保存</el-button>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance } from 'element-plus'
import type { ServiceFee, ServiceRate, DepositRate } from '@/types/extraService'
import { baseSettingsService } from '@/services/baseSettingsService'
import { User, UserFilled, Platform, Plus, Edit, Delete } from '@element-plus/icons-vue'

// 当前激活的标签页
const activeTab = ref('service-fee')

// 手续费数据 - 从基础设置服务加载
const serviceFeeList = ref<ServiceFee[]>([])

// 服务费率数据 - 从基础设置服务加载
const serviceRateList = ref<ServiceRate[]>([])

// 保证金比例数据 - 从基础设置服务加载
const depositRateList = ref<DepositRate[]>([])

// 站点选项
const siteOptions = ref([
  { label: '煤炉', value: '煤炉' },
  { label: '雅虎日拍', value: '雅虎日拍' },
  { label: '雅虎闲置', value: '雅虎闲置' },
  { label: '煤炉闲置', value: '煤炉闲置' },
  { label: '亚马逊日本', value: '亚马逊日本' },
  { label: '乐天市场', value: '乐天市场' },
  { label: 'Sofmap', value: 'Sofmap' },
  { label: 'SKiT', value: 'SKiT' },
  { label: 'Skitdolce', value: 'Skitdolce' },
  { label: 'Tohoanima', value: 'Tohoanima' },
  { label: 'Kotobukiya', value: 'Kotobukiya' },
  { label: 'JUMP SHO！', value: 'JUMP SHO！' },
  { label: 'CCO', value: 'CCO' },
  { label: 'Store', value: 'Store' },
  { label: 'ANIPLEX+', value: 'ANIPLEX+' },
  { label: 'm78', value: 'm78' },
  { label: 'Eeo', value: 'Eeo' },
  { label: 'AnimeCollection', value: 'AnimeCollection' },
  { label: 'Chara-Ani', value: 'Chara-Ani' },
  { label: 'Amnibus', value: 'Amnibus' },
  { label: 'Kyoanishop', value: 'Kyoanishop' },
  { label: 'Movic', value: 'Movic' }
])

// 当前选中的站点
const selectedSite = ref('all')

// 初始化数据
onMounted(() => {
  loadSettingsFromService()
})

// 从基础设置服务加载数据
function loadSettingsFromService() {
  // 加载手续费设置
  const serviceFees = baseSettingsService.getServiceFeeSettings()
  serviceFeeList.value = serviceFees.map(item => ({
    id: item.id,
    type: item.type,
    site: item.site, // 添加站点
    minAmount: item.minAmount || 0,
    maxAmount: item.maxAmount,
    fee: item.fee
  }))

  // 加载服务费率设置
  const serviceRates = baseSettingsService.getServiceRateSettings()
  serviceRateList.value = serviceRates.map(item => ({
    id: item.id,
    site: item.site,
    rate: item.rate,
    remark: item.remark || ''
  }))

  // 加载保证金比例设置
  const depositRates = baseSettingsService.getDepositRateSettings()
  depositRateList.value = depositRates.map(item => ({
    id: item.id,
    site: item.site,
    rate: item.rate,
    remark: item.remark || ''
  }))
}

// 手续费相关弹窗
const serviceFeeDialog = reactive({
  visible: false,
  mode: 'add' as 'add' | 'edit',
  form: {
    id: '',
    type: 'B' as 'B' | 'C',
    site: '', // 添加站点
    minAmount: 0,
    maxAmount: null as number | null,
    fee: 0
  },
  editIndex: -1
})

const serviceFeeFormRef = ref<FormInstance>()

const serviceFeeRules = {
  minAmount: [{ required: true, message: '请输入区间下限', trigger: 'blur' }],
  fee: [{ required: true, message: '请输入手续费', trigger: 'blur' }],
  type: [{ required: true, message: '请选择客户类型', trigger: 'change' }],
  site: [{ required: true, message: '请选择站点', trigger: 'change' }]
}

// 服务费率弹窗
const serviceRateDialog = reactive({
  visible: false,
  mode: 'add' as 'add' | 'edit',
  form: {
    id: '',
    site: '',
    rate: 0,
    remark: ''
  },
  editIndex: -1
})

const serviceRateFormRef = ref<FormInstance>()

const serviceRateRules = {
  site: [{ required: true, message: '请选择站点', trigger: 'change' }],
  rate: [{ required: true, message: '请输入费率', trigger: 'blur' }]
}

// 保证金比例弹窗
const depositRateDialog = reactive({
  visible: false,
  mode: 'add' as 'add' | 'edit',
  form: {
    id: '',
    site: '',
    rate: 0,
    remark: ''
  },
  editIndex: -1
})

const depositRateFormRef = ref<FormInstance>()

const depositRateRules = {
  site: [{ required: true, message: '请选择站点', trigger: 'change' }],
  rate: [{ required: true, message: '请输入保证金比例', trigger: 'blur' }]
}

// 手续费相关方法
function openServiceFeeDialog(mode: 'add' | 'edit', type?: 'B' | 'C', row?: ServiceFee, idx?: number, site?: string) {
  serviceFeeDialog.mode = mode
  if (mode === 'add') {
    serviceFeeDialog.form = {
      id: '',
      type: type || 'B',
      site: site || siteOptions.value[0]?.value || '', // 默认选择第一个站点
      minAmount: 0,
      maxAmount: null,
      fee: 0
    }
    serviceFeeDialog.editIndex = -1
  } else if (row && typeof idx === 'number') {
    serviceFeeDialog.form = { ...row }
    serviceFeeDialog.editIndex = idx
  }
  serviceFeeDialog.visible = true
}

function saveServiceFee() {
  serviceFeeFormRef.value?.validate((valid: boolean) => {
    if (!valid) return

    const idx = serviceFeeDialog.editIndex
    if (serviceFeeDialog.mode === 'add') {
      // 添加到基础设置服务
      baseSettingsService.addServiceFeeSetting({
        type: serviceFeeDialog.form.type,
        site: serviceFeeDialog.form.site, // 添加站点
        minAmount: serviceFeeDialog.form.minAmount,
        maxAmount: serviceFeeDialog.form.maxAmount,
        fee: serviceFeeDialog.form.fee
      })
      // 重新加载数据
      loadSettingsFromService()
      ElMessage.success('新增成功')
    } else if (idx > -1) {
      // 更新基础设置服务
      const item = serviceFeeList.value[idx]
      baseSettingsService.updateServiceFeeSetting(item.id, {
        type: serviceFeeDialog.form.type,
        site: serviceFeeDialog.form.site, // 添加站点
        minAmount: serviceFeeDialog.form.minAmount,
        maxAmount: serviceFeeDialog.form.maxAmount,
        fee: serviceFeeDialog.form.fee
      })
      // 重新加载数据
      loadSettingsFromService()
      ElMessage.success('编辑成功')
    }
    serviceFeeDialog.visible = false
  })
}

function deleteServiceFee(row: ServiceFee, idx: number) {
  ElMessageBox.confirm(
    `确定要删除这条手续费设置吗？`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 从基础设置服务删除
    baseSettingsService.deleteServiceFeeSetting(row.id)
    // 重新加载数据
    loadSettingsFromService()
    ElMessage.success('删除成功')
  })
}

// 服务费率相关方法
function openServiceRateDialog(mode: 'add' | 'edit', row?: ServiceRate, idx?: number) {
  serviceRateDialog.mode = mode
  if (mode === 'add') {
    serviceRateDialog.form = {
      id: '',
      site: '',
      rate: 0,
      remark: ''
    }
    serviceRateDialog.editIndex = -1
  } else if (row && typeof idx === 'number') {
    serviceRateDialog.form = { ...row }
    serviceRateDialog.editIndex = idx
  }
  serviceRateDialog.visible = true
}

function saveServiceRate() {
  serviceRateFormRef.value?.validate((valid: boolean) => {
    if (!valid) return

    const idx = serviceRateDialog.editIndex
    if (serviceRateDialog.mode === 'add') {
      const newId = (Math.max(...serviceRateList.value.map(i => Number(i.id)), 0) + 1).toString()
      serviceRateList.value.push({ ...serviceRateDialog.form, id: newId })
      ElMessage.success('新增成功')
    } else if (idx > -1) {
      serviceRateList.value[idx] = { ...serviceRateDialog.form }
      ElMessage.success('编辑成功')
    }
    serviceRateDialog.visible = false
  })
}

function deleteServiceRate(row: ServiceRate, idx: number) {
  ElMessageBox.confirm(
    `确定要删除这条服务费率设置吗？`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    serviceRateList.value.splice(idx, 1)
    ElMessage.success('删除成功')
  })
}

// 保证金比例相关方法
function openDepositRateDialog(mode: 'add' | 'edit', row?: DepositRate, idx?: number) {
  depositRateDialog.mode = mode
  if (mode === 'add') {
    depositRateDialog.form = {
      id: '',
      site: '',
      rate: 0,
      remark: ''
    }
    depositRateDialog.editIndex = -1
  } else if (row && typeof idx === 'number') {
    depositRateDialog.form = { ...row }
    depositRateDialog.editIndex = idx
  }
  depositRateDialog.visible = true
}

function saveDepositRate() {
  depositRateFormRef.value?.validate((valid: boolean) => {
    if (!valid) return

    const idx = depositRateDialog.editIndex
    if (depositRateDialog.mode === 'add') {
      const newId = (Math.max(...depositRateList.value.map(i => Number(i.id)), 0) + 1).toString()
      depositRateList.value.push({ ...depositRateDialog.form, id: newId })
      ElMessage.success('新增成功')
    } else if (idx > -1) {
      depositRateList.value[idx] = { ...depositRateDialog.form }
      ElMessage.success('编辑成功')
    }
    depositRateDialog.visible = false
  })
}

function deleteDepositRate(row: DepositRate, idx: number) {
  ElMessageBox.confirm(
    `确定要删除这条保证金比例设置吗？`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    depositRateList.value.splice(idx, 1)
    ElMessage.success('删除成功')
  })
}

// 辅助函数
function getUniqueSites(type: 'B' | 'C') {
  const sites = serviceFeeList.value
    .filter(item => item.type === type)
    .map(item => item.site)
  return [...new Set(sites)]
}

function getServiceFeesBySite(type: 'B' | 'C', site: string) {
  return serviceFeeList.value.filter(item => item.type === type && item.site === site)
}

function getSiteLabel(site: string) {
  const option = siteOptions.value.find(opt => opt.value === site)
  return option ? option.label : site
}

function onSiteChange(value: string) {
  selectedSite.value = value
}
</script>

<style scoped>
.extra-service {
  padding: 16px;
}

.section {
  margin-bottom: 32px;
}

.section:last-child {
  margin-bottom: 0;
}

.section-title {
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  border-bottom: 2px solid #409eff;
  padding-bottom: 8px;
}

.subsection {
  margin-bottom: 24px;
}

.subsection:last-child {
  margin-bottom: 0;
}

.subsection-title {
  margin: 0 0 12px 0;
  font-size: 14px;
  font-weight: 500;
  color: #606266;
  border-bottom: 1px solid #e4e7ed;
  padding-bottom: 6px;
}

.table-actions {
  margin-bottom: 12px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.action-buttons {
  display: flex;
  gap: 8px;
  align-items: center;
}

.site-selector {
  margin-bottom: 20px;
}

.site-stats {
  margin-top: 10px;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.site-groups {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.site-group {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 20px;
  background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.site-group:hover {
  box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.15);
  transform: translateY(-2px);
}

.site-group-title {
  margin: 0 0 20px 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  border-bottom: 2px solid #409eff;
  padding-bottom: 12px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.site-group-title .el-icon {
  color: #409eff;
  font-size: 20px;
}

.site-section {
  margin-bottom: 24px;
  padding: 16px;
  background: #ffffff;
  border-radius: 6px;
  border: 1px solid #f0f0f0;
}

.site-section:last-child {
  margin-bottom: 0;
}

.site-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.site-name {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin: 0;
  display: flex;
  align-items: center;
  gap: 8px;
}

.site-name .el-icon {
  color: #67c23a;
  font-size: 18px;
}

.single-site {
  padding: 24px;
  background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.site-header h3 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 10px;
}

.site-header h3 .el-icon {
  color: #409eff;
  font-size: 24px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.custom-table {
  border-collapse: collapse;
  width: 100%;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 1px 4px 0 rgba(0, 0, 0, 0.1);
}

.custom-table th,
.custom-table td {
  padding: 16px 20px;
  text-align: center;
  border-bottom: 1px solid #f0f0f0;
}

.custom-table th {
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e7ed 100%);
  font-weight: 600;
  color: #303133;
  font-size: 14px;
}

.custom-table tr:last-child td {
  border-bottom: none;
}

.custom-table tr:hover {
  background: linear-gradient(135deg, #f5f7fa 0%, #e8f4fd 100%);
  transition: background 0.3s ease;
}

.amount-text {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
}

.fee-text {
  font-size: 16px;
  color: #409eff;
  font-weight: 600;
}

.no-limit {
  font-size: 14px;
  color: #909399;
  font-style: italic;
}

.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
}

.action-buttons .el-button {
  border-radius: 6px;
  font-weight: 500;
}

.empty-state {
  padding: 40px 20px;
  text-align: center;
  background: #fafafa;
  border-radius: 6px;
  border: 1px dashed #d9d9d9;
}

.empty-state .el-empty__description {
  color: #909399;
  font-size: 14px;
  margin-bottom: 20px;
}

.empty-state .el-button {
  border-radius: 20px;
  padding: 8px 20px;
}
</style> 